package com.zym.init.core.auth;

import com.alibaba.fastjson2.JSONObject;
import com.zym.init.core.domain.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * 认证失败处理器
 * 当用户请求需要认证的资源但是他们没有认证时，这个入口点会被调用。
 */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * 处理未认证
     *
     * @param request       that resulted in an <code>AuthenticationException</code>
     * @param response      so that the user agent can begin authentication
     * @param authException that caused the invocation
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        AjaxResult result = AjaxResult.login();
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}
